<template>
  <div class="department-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数：{{total}}</span>
        </template>

        <!-- 插入到right插槽位置 -->
        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/import')">导入excel</el-button>
          <el-button type="danger" size="small" @click="handleDownload">导出excel</el-button>
          <el-button type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table :data="list" border :default-sort="{prop:'timeOfEntry',order:'ascending'}">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column sortable label="工号" prop="workNumber" />
          <el-table-column label="头像">
            <template #default="{row}">
              <img :src="row.staffPhoto" alt style="width:100%" />
            </template>
          </el-table-column>
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="{row}">{{formOfEmploymentFormat(row.formOfEmployment)}}</template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column sortable label="入职时间" prop="timeOfEntry" />
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail/${row.id}`)"
              >查看</el-button>
              <el-button type="text" size="small" @click="hAssignRole(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="page"
            :page-sizes="[2,3,5,10]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          />
        </el-row>
      </el-card>

      <el-dialog title="新增员工" :visible.sync="showDialog" @close="hResetForm">
        <addEmployees ref="addEmployees" @close="showDialog=false" @success="hSuccess" />
      </el-dialog>
      
      <!-- 分配角色的弹层 -->
      <el-dialog title="分配角色" :visible.sync="roleShowDialog">
        <assignRole v-if="roleShowDialog" :id="curId" @success="hAssignRoleSuccess"/>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import assignRole from "./assignRole.vue";
import addEmployees from "./empDialog.vue";
// import PageTools from '@/components/PageTools'
import { getEmployees, delEmployee } from "@/api/employees";
import EmployeesEnum from "@/constant/employees";

// console.log('EmployeesEnum.hireType',EmployeesEnum.hireType);

// const hireType={}
// EmployeesEnum.hireType.forEach(item=>{
//   hireType[item.id]=item.value
// })
const hireType = EmployeesEnum.hireType.reduce((acc, item) => {
  acc[item.id] = item.value;
  return acc;
}, {});

console.log("hireType", hireType);
export default {
  name: "Employees",
  components: {
    addEmployees,
    assignRole
  },
  data() {
    return {
      roleShowDialog:false,
      showDialog: false,
      page: 1,
      size: 2,
      list: [],//保存员工的数据
      total: 0,//保存员工的总数
      curId:''//保存员工的id
    };
  },
  created() {
    this.loadEmployees();
  },
  methods: {
    // 关闭分配角色的弹层
    hAssignRoleSuccess(){
      this.roleShowDialog=false
    },
    hAssignRole(id){
      this.roleShowDialog=true
      this.curId=id
    },
    formatdata(list) {
      // 1.根据数据对象的键根据映射关系，得到一个中文的键，放到一个数组里--header['编号','密码']
      // 2.将每一个对象的值，存到一个数组中，所有的结果放入到一个大数组里--data[["2018-11-30,"总裁办"]]
      const map = {
        id: "编号",
        password: "密码",
        mobile: "手机号",
        username: "姓名",
        timeOfEntry: "入职日期",
        formOfEmployment: "聘用形式",
        correctionTime: "转正日期",
        workNumber: "工号",
        departmentName: "部门",
        staffPhoto: "头像地址"
      };

      const one = list[0];

      if (!one) return;
      //             id,password
      const header = Object.keys(one).map(enkey => {
        return map[enkey]; //编号,密码
      });

      const data = list.map(item => {
        const key = item.formOfEmployment; // 1 || 2
        item["formOfEmployment"] = hireType[key] || "未知";
        return Object.values(item);
      });
      return { header: header, data: data };
    },
    //导入功能的关键代码
    async handleDownload() {
      const res = await getEmployees(this.page, this.size);
      console.log("res.data.rows", res.data.rows);
      const { header, data } = this.formatdata(res.data.rows);
      // console.log('hd',{ header, data });
      // import ('@/vendor/Export2Excel')懒加载的方式导入一个模块（文件）返回值是一个promise实例
      import("@/vendor/Export2Excel").then(excel => {
        //excel指的是模块对象，可以使用excel调用Export2Excel文件中的函数或者使用其变量
        excel.export_json_to_excel({
          header: header,
          data: data,
          filename: this.filename,
          autoWidth: this.autoWidth,
          bookType: this.bookType
        });
      });
    },
    // 删除
    hDel(id) {
      this.$confirm("确认删除?")
        .then(async () => {
          await delEmployee(id);
          // 判断页面是否只有一条数据
          if (this.list.length === 1) {
            this.page--;
            if (this.page <= 0) {
              this.page = 1;
            }
          }
          this.loadEmployees();
        })
        .catch(error => {
          console.log(error);
        });
    },
    hResetForm() {
      // 重置表单，表单是子组件
      // this.$refs.子组件名.子组件方法
      this.$refs.addEmployees.resetForm();
    },
    // 成功添加后
    hSuccess() {
      // 计算出最大的页码值
      this.total++;
      // 向上取整
      const maxPage = Math.ceil(this.total / this.size);
      this.page = maxPage;
      // 重新渲染
      this.loadEmployees();
      // 关闭弹层
      this.showDialog = false;
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.page = 1;
      this.size = val;
      this.loadEmployees();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.page = val;
      this.loadEmployees();
    },

    // 格式化聘用形式的函数
    formOfEmploymentFormat(data) {
      // return EmployeesEnum.hireType.find(item=>item.id===data).value
      return hireType[data] || "未知";
    },
    async loadEmployees() {
      try {
        const res = await getEmployees(this.page, this.size);
        console.log("res", res);
        this.list = res.data.rows;
        this.total = res.data.total;
      } catch (error) {
        console.log(error);
      }
    }
  }
};
</script>